<?php

namespace App\Models\Admin\Authority;

class AuthorityMenusModel extends BaseAuthorityModel
{
    protected $table = 'authority_menus';

    /**
     * 根据角色id查询数据
     *
     * @param int $authorityId
     * @return array
     */
    public function getMenusIdsByAuthorityId(int $authorityId): array
    {
        return $this->where('authority_id', $authorityId)
            ->pluck('menu_id')
            ->toArray();
    }

    /**
     * 根据菜单id将数据标为删除
     *
     * @param int $menuId
     * @return int
     */
    public function deleteItemByMenuId(int $menuId): int
    {
        return $this->where('menu_id', $menuId)->delete();
    }

    /**
     * 根据角色id将数据标记为删除
     *
     * @param int $authorityId 角色id
     * @return int
     */
    public function deleteItemByAuthorityId(int $authorityId): int
    {
        return $this->where('authority_id', $authorityId)
            ->delete();
    }

    /**
     * 根据角色id和菜单ids 删除
     *
     * @param int   $authorityId
     * @param array $menuIds
     * @return int
     */
    public function deleteItemByAuthorityIdAndMenuIds(int $authorityId, array $menuIds): int
    {
        return $this->where('authority_id', $authorityId)
            ->whereIn('menu_id', $menuIds)
            ->where('deleted', self::DELETED_NO)
            ->update([
                'deleted' => self::DELETED_YES,
            ]);
    }

    /**
     * 获取列表
     *
     * @param int      $authorityId
     * @param string[] $fields
     * @return array
     */
    public function getItemsByAuthorityId(int $authorityId, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        return $this->select($fields)
            ->where('authority_id', $authorityId)
            ->get()
            ->toArray();
    }

    /**
     * 添加数据【可添加多条】
     *
     * @param array $params
     * @return int
     */
    public function addItem(array $params): int
    {
        if (isset($params[0]) && is_array($params[0])) {
            foreach ($params as $index => $item) {
                $params[$index]['created_at'] = DATE_NOW;
            }
        } else {
            $params['created_at'] = DATE_NOW;
        }

        return $this->insert($params);
    }
}
